<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备名称" prop="reName">
        <el-input v-model="queryParams.reName" placeholder="请输入设备名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="设备型号" prop="reModel">
        <el-input v-model="queryParams.reModel" placeholder="请输入设备型号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="设备状态" prop="reState">
        <el-select v-model="queryParams.reState" placeholder="请选择设备状态" clearable>
          <el-option v-for="dict in dict.type.eamp_re_state" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="使用状态" prop="reUseState">
        <el-select v-model="queryParams.reUseState" placeholder="请选择使用状态" clearable>
          <el-option v-for="dict in dict.type.eamp_re_use_state" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['eamp:re_man:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['eamp:re_man:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['eamp:re_man:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['eamp:re_man:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="re_manList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="reId" />
      <el-table-column label="设备名称" align="center" prop="reName" />
      <el-table-column label="设备型号" align="center" prop="reModel" />
      <el-table-column label="存放位置" align="center">
        <template slot-scope="scope">
          {{ getWarehouseName(scope.row.reSrId) }}
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="reCreateBy">
        <template slot-scope="scope">
          {{ getUserName(scope.row.reCreateBy) }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="reCreateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.reCreateTime, "{y}-{m}-{d} {h}:{i}:{s}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="设备状态" align="center" prop="reState">
        <template slot-scope="scope">
          {{ getStateDictLabel(scope.row.reState, stateDictList) }}
        </template>
      </el-table-column>
      <el-table-column label="使用状态" align="center" prop="reUseState">
        <template slot-scope="scope">
          {{ getUseDictLabel(scope.row.reUseState, useDictList) }}
        </template>
      </el-table-column>
      <el-table-column label="实验结果" align="center" prop="reExResults">
        <template slot-scope="scope">
          {{ getResultDictLabel(scope.row.reExResults, resultDictList) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleApplyExperiment(scope.row)"
            v-show="scope.row.reState == 0 && scope.row.reUseState != 0">申请实验</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleResultsExperiment(scope.row)"
            v-show="scope.row.reState != 0">实验结果</el-button>
          <el-button size="mini" type="text" icon="el-icon-box" @click="handleStockOut(scope.row)"
            v-show="scope.row.reState == 1 && scope.row.reUseState == 2">出库</el-button>
          <el-button v-show="scope.row.reState == 0" size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['eamp:re_man:edit']" >修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['eamp:re_man:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改参试设备表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备名称" prop="reName">
          <el-input v-model="form.reName" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="设备型号" prop="reModel">
          <el-input v-model="form.reModel" placeholder="请输入设备型号" />
        </el-form-item>
        <el-form-item label="库房" prop="reSrId">
          <el-select v-model="form.reSrId" placeholder="请选择存放位置">
            <el-option v-for="item in sr_list" :key="item.srId" :label="item.srName" :value="item.srId" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备状态" prop="reState">
          <el-select v-model="form.reState" placeholder="请选择设备状态">
            <el-option v-for="dict in dict.type.eamp_re_state" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="使用状态" prop="reUseState">
          <el-select v-model="form.reUseState" placeholder="请选择使用状态">
            <el-option v-for="dict in dict.type.eamp_re_use_state" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属部门" prop="reDeptId">
          <el-select v-model="form.reDeptId" placeholder="请输入所属部门">
            <el-option v-for="item in dept_List" :key="item.deptId" :label="item.deptName" :value="item.deptId" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备附件" prop="reFile">
          <file-upload v-model="form.reFile" />
        </el-form-item>
        <el-form-item label="设备备注" prop="reRemark">
          <el-input v-model="form.reRemark" placeholder="请输入设备备注" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看详细信息 -->
    <el-dialog :title="title" :visible.sync="dialogView" width="500px" append-to-body>
      <el-form :model="form" label-width="80px" :disabled="true">
        <el-form-item label="设备名称">
          <el-input v-model="form.reName" placeholder="请输入设备名称" disabled />
        </el-form-item>
        <el-form-item label="设备型号">
          <el-input v-model="form.reModel" placeholder="请输入设备型号" disabled />
        </el-form-item>
        <el-form-item label="库房">
          <el-select v-model="form.reSrId" placeholder="请选择存放位置" disabled>
            <el-option v-for="item in sr_list" :key="item.srId" :label="item.srName" :value="item.srId" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备状态">
          <el-select v-model="form.reState" placeholder="请选择设备状态" disabled>
            <el-option v-for="dict in dict.type.eamp_re_state" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="使用状态">
          <el-select v-model="form.reUseState" placeholder="请选择使用状态" disabled>
            <el-option v-for="dict in dict.type.eamp_re_use_state" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属部门">
          <el-select v-model="form.reDeptId" placeholder="请输入所属部门" disabled>
            <el-option v-for="item in dept_List" :key="item.deptId" :label="item.deptName" :value="item.deptId" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备附件" prop="reFile">
          <template>
            <file-upload v-model="form.reFile" v-if="form.reFile" />
            <div v-else>无文件上传</div>
            <!-- <div>{{ form.srFile ? form.srFile : "无文件上传" }} prop="reFile"</div> -->
          </template>
        </el-form-item>
        <el-form-item label="设备备注">
          <el-input v-model="form.reRemark" placeholder="请输入设备备注" type="textarea" disabled />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="Viewcancel">关 闭</el-button>
      </div>
    </el-dialog>

    <!--申请实验按钮弹窗-->
    <el-dialog title="确认" :visible.sync="dialogVisible" width="30%" @close="resetDialog">
      <p>确定要进行申请实验吗？</p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </span>
    </el-dialog>

    <!--实验结果按钮弹窗-->
    <el-dialog title="确认" :visible.sync="dialogResult" width="30%">
      <el-select v-model="form.reExResults" placeholder="请选择实验结果" clearable>
        <el-option v-for="dict in dict.type.eamp_re_ex_results" :key="dict.value" :label="dict.label"
          :value="dict.value" />
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resultCancel">取消</el-button>
        <el-button type="primary" @click="resultConfirm">确定</el-button>
      </span>
    </el-dialog>

    <!--出库按钮弹窗-->
    <el-dialog title="确认" :visible.sync="dialogStockOut" width="30%">
      <h2>是否确定出库</h2>
      <span slot="footer" class="dialog-footer">
        <el-button @click="stockCancel">取消</el-button>
        <el-button type="primary" @click="stockConfirm">确定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import {
  listRe_man,
  getRe_man,
  delRe_man,
  addRe_man,
  updateRe_man,
  srList,
  reList,
  deptList,
  updateState,
  updateResult,
  updateStock,
} from "@/api/eamp/re_man";
import { getDicts } from "@/api/system/dict/data";
import { listUser } from "@/api/system/user";
export default {
  dicts: ["eamp_re_use_state", "eamp_re_state", "eamp_re_ex_results"],
  name: "Re_man",
  data() {
    return {
      dialogView: false,//查看详细信息弹窗控制
      dialogResult: false, //实验结果弹窗控制
      dialogVisible: false, //申请实验弹窗控制
      dialogStockOut: false, //出库弹窗控制
      currentReId: null, // 用于存储当前要更新的 reId
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户列表
      user_List: [],
      // 库房列表
      sr_list: [],
      // 部门列表
      dept_List: [],
      // 设备不分页列表
      reList: [],
      // 参试设备表表格数据
      re_manList: [],
      // 字典值
      stateDictList: [],
      useDictList: [],
      resultDictList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        reName: null,
        reModel: null,
        reSrId: null,
        reCreateBy: null,
        reCreateTime: null,
        reState: null,
        reUseState: null,
        reDeptId: null,
        reFile: null,
        reRemark: null,
        delFlg: 1,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        reName: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ],
        reModel: [
          { required: true, message: '类型不能为空', trigger: 'blur' }
        ],
        reSrId: [
          { required: true, message: '存放位置不能为空', trigger: 'blur' }
        ],
        reState: [
          { required: true, message: '存放位置不能为空', trigger: 'blur' }
        ],
        reUseState: [
          { required: true, message: '存放位置不能为空', trigger: 'blur' }
        ]
      },
      originalWarehouse: null,
      modifiedWarehouse: null,
    };
  },
  created() {
    this.getList();
    this.getSrList();
    this.getReList();
    this.getDeptList();
    this.getDictList();
    this.getUserList();
  },
  watch: {
    "form.reSrId": function (newValue, oldValue) {
      // console.log('修改前的值:', oldValue);
      // console.log('修改后的值:', newValue);
      // 可以将这两个值赋给原库房号和修改后的库房号的变量
      this.originalWarehouse = oldValue;
      this.modifiedWarehouse = newValue;
    },
  },
  methods: {
    // 获取不分页的设备列表
    getReList() {
      reList().then(res => {
        this.reList = res.rows;
      })
    },
    // 获取用户列表
    getUserList() {
      listUser().then((response) => {
        this.user_List = response.rows;
        // console.log(this.user_List);
      });
    },
    getUserName(uId) {
      const user = this.user_List.find((item) => item.userId == uId);
      return user ? user.userName : "";
    },
    // 表格获取当前使用状态
    getUseDictLabel(reUseState, useDictList) {
      const useDict = useDictList.find((dict) => dict.dictValue == reUseState);
      return useDict ? useDict.dictLabel : "";
    },
    // 表格获取当前设备状态
    getStateDictLabel(reState, stateDictList) {
      const useDict = stateDictList.find((dict) => dict.dictValue == reState);
      return useDict ? useDict.dictLabel : "";
    },
    // 表格获取当前实验结果
    getResultDictLabel(reExResults, resultDictList) {
      const resultDict = resultDictList.find(
        (dict) => dict.dictValue == reExResults
      );
      return resultDict ? resultDict.dictLabel : "";
    },
    // 获取字典列表
    getDictList() {
      getDicts("eamp_re_state").then((res) => {
        this.stateDictList = res.data;
        // console.log(this.stateDictList)
      });
      getDicts("eamp_re_use_state").then((res) => {
        this.useDictList = res.data;
        // console.log(this.useDictList)
      });
      getDicts("eamp_re_ex_results").then((res) => {
        this.resultDictList = res.data;
      });
    },

    // 查询库房列表
    getSrList() {
      // 查询库房列表
      srList().then((response) => {
        this.sr_list = response.rows.filter((item) => item.delFlg === 1);
        // console.log(this.sr_list);
      });
    },
    // 获取库房信息
    getWarehouseName(srId) {
      const warehouse = this.sr_list.find((item) => item.srId === srId);
      return warehouse ? warehouse.srName : "";
    },

    // 查询部门列表
    getDeptList() {
      deptList().then((response) => {
        this.dept_List = response.data;
        // console.log(this.dept_List);
      });
    },

    /** 查询参试设备表列表 */
    getList() {
      this.loading = true;
      listRe_man(this.queryParams).then((response) => {
        this.re_manList = response.rows;
        // console.log(this.re_manList);
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        reId: null,
        reName: null,
        reModel: null,
        reSrId: null,
        reCreateBy: null,
        reCreateTime: null,
        reState: null,
        reUseState: null,
        reDeptId: null,
        reFile: null,
        reRemark: null,
        delFlg: 1,
      };
      this.resetForm("form");
    },

    // 查看按钮
    handleView(row) {
      this.form = row;
      this.dialogView = true; // 打开弹窗层
    },
    Viewcancel() {
      this.dialogView = false;
    },

    // 申请实验按钮操作
    handleApplyExperiment(row) {
      // 弹出确认框
      this.currentReId = row.reId; // 保存当前 reId
      this.dialogVisible = true; // 显示弹窗
    },
    handleConfirm() {
      updateState(this.currentReId).then((response) => {
        // this.form = response.data;
        this.getList(); // 更新列表
        this.dialogVisible = false; // 关闭弹窗
      });
    },
    handleCancel() {
      this.dialogVisible = false; // 关闭弹窗
    },
    resetDialog() {
      this.currentReId = null; // 重置 reId
    },

    // 实验结果按钮操作
    handleResultsExperiment(row) {
      this.currentReId = row.reId;
      this.dialogResult = true;
    },
    resultConfirm() {
      updateResult(this.currentReId, this.form).then((response) => {
        this.getList();
        this.dialogResult = false;
      });
    },
    resultCancel() {
      this.dialogResult = false; // 关闭弹窗
      this.getList();
    },

    /* 出库按钮 */
    handleStockOut(row) {
      this.currentReId = row.reId;
      // console.log(row.reUseState);

      this.dialogStockOut = true;
    },
    stockConfirm() {
      updateStock(this.currentReId).then((response) => {
        // console.log(response.data);
        this.$modal.msgSuccess("出库成功");
        this.getList();
        this.dialogStockOut = false;
      });
    },
    stockCancel() {
      this.dialogStockOut = false; // 关闭弹窗
      this.getList();
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.reId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加参试设备表";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const reId = row.reId || this.ids;
      getRe_man(reId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改参试设备表";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.reId != null) {
            const foundWarehouse = this.sr_list.find(warehouse => warehouse.srId == this.form.reSrId);
            if (foundWarehouse) {
              console.log("修改前的值:", this.originalWarehouse); // 打印修改前的值  
              console.log("修改后的值:", this.modifiedWarehouse); // 打印修改后的值  
              // 检查当前规格是否为 0  
              if (foundWarehouse.srCurrentSpecifications === 0) {
                this.$message.error('库房的当前规格为0，无法进行修改');
                return; // 终止操作  
              }
              var data = {
                originalWarehouse: this.originalWarehouse,
                modifiedWarehouse: this.modifiedWarehouse,
                eampReMan: this.form,
              };
              updateRe_man(data).then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              this.$message.error('未找到对应的库房信息');
            }
          } else {
            if (this.reList.find(item => item.reName == this.form.reName)) {
              this.$message.error('参试设备名称已存在,无法重复添加');
            } else {
              // 通过库房列表（sr_list）找到对应的库房信息
              const foundWarehouse = this.sr_list.find(warehouse => warehouse.srId == this.form.reSrId);
              // 检查要存入的库房的当前规格是否满足
              if (foundWarehouse && foundWarehouse.srCurrentSpecifications != 0) {
                // 执行新增操作
                addRe_man(this.form).then((response) => {
                  this.$modal.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                });
              } else {
                this.$message.error('库房的当前规格不满足要求');
              }
            }
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const reIds = row.reId || this.ids;
      this.$modal
        .confirm('是否确认删除参试设备表编号为"' + reIds + '"的数据项？')
        .then(function () {
          return delRe_man(reIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "eamp/re_man/export",
        {
          ...this.queryParams,
        },
        `re_man_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
